package com.itheima.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer_HelloWorld {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost("192.168.88.128");//设置IP地址
        factory.setPort(5672);//设置端口
        factory.setVirtualHost("/itcast");//虚拟机    默认值为/
        factory.setUsername("heima");//用户名
        factory.setPassword("heima");//密码
        //3.创建链接  Connection
        Connection connection = factory.newConnection();
        //4.创建Channel
        Channel channel = connection.createChannel();
        //5.创建队列Queue
        /*
        queueDeclare(
            String queue,       队列名称
            boolean durable,    是否持久化,当mq重启之后还在
            boolean exclusive,  1.是否独占,只能有一个消费者监听折队列  2.当connection关闭时,是否删除队列
            boolean autoDelete, 是否自动删除.当没有consumer时,自动删除
            Map<String, Object> arguments)  参数
         */
        //注意:如果该名称队列如果存在,不会创建,如果不存在才会创建
        channel.queueDeclare("hello_world",true,false,false,null);
        //接收消息
        Consumer consumer = new DefaultConsumer(channel){
            //这是一个回调方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag:"+consumerTag);
                System.out.println("Exchange:"+envelope.getExchange());
                System.out.println("RoutingKey:"+envelope.getRoutingKey());
                System.out.println("properties:"+properties);
                System.out.println("body:"+new String(body));
            }
        };
        channel.basicConsume("hello_world",true,consumer);
    }
}
